<template>
	<view v-if="orderInfo">
		<!-- 问诊订单状态 -->
		<view class="top-warp" style="padding-top:1px;">
			<!-- 病人详情 -->
			<view class="jzr_info" v-if="isDoc==1 && orderInfo.user_the_patient_info" @click="toHz">
				{{orderInfo.user_the_patient_info.name}}<text>{{orderInfo.user_the_patient_info.sex==1?'男':'女'}}</text>{{orderInfo.user_the_patient_info.age}}岁
				<view>查看病人详情 > </view>
			</view>
		</view>

		<!-- 聊天窗口 -->
		<view class="content">
			<scroll-view class="list-warp" scroll-y="true" upper-threshold="50" style="top:110rpx;bottom:0rpx;padding-bottom:0;"
				:scroll-with-animation="scrollAnimation"
				:scroll-top="scrollTop"
				:scroll-into-view="scrollToView"
				@scrolltoupper="loadHistory">

				<!-- 加载历史数据waitingUI -->
				<block v-if="isHistoryLoading == true">
					<view class="loading">
						<view class="spinner">
							<view class="rect1"></view>
							<view class="rect2"></view>
							<view class="rect3"></view>
							<view class="rect4"></view>
							<view class="rect5"></view>
						</view>
					</view>
				</block>

				<view class="item" v-for="(item,index) in chatList" :key="index" :id="'chat-'+index">
					<!-- 系统消息 时间/提示 -->
					<view class="system-chat" v-if="item.fromType=='system'">
						<!-- 待接诊 -->
						<view class="waiting-for-treatment" v-if="item.type=='waiting-for-treatment' && orderStatus==0">待接诊，{{downTimeTxt}}后未接诊将自动退诊</view>
						<!-- 提示 -->
						<view class="tip" v-if="item.type=='tip'">{{item.content.text}}</view>
						<!-- 时间 -->
						<view class="time" v-if="item.type=='time'">{{item.content.text}}</view>
					</view>
					<!-- 用户消息 -->
					<view :class="'user-chat '+(((isDoc==1?item.from.prefix=='DT':item.from.prefix=='HZ')&&item.from.uid==FromUser.uid)?'my':'other')" v-if="item.fromType=='user'">
						<!-- 左-头像 -->
						<!--  -->
						<view class="avatar"><image :src="ToUser.avatar" v-if="!((isDoc==1?item.from.prefix=='DT':item.from.prefix=='HZ')&&item.from.uid==FromUser.uid)"></image></view>

						<view class="content-outer">
							<view class="content-inner">
								<!-- 文字卡片 -->
								<view class="textCard" v-if="item.type=='textCard'">
									<view class="row" v-for="(n,v) in item.content.list" :key="v">
										<view class="left">{{n.name}}:</view>
										<view class="right">{{n.value}}</view>
									</view>
								</view>
								<!-- 多图 -->
								<view class="imgs" v-if="item.type=='imgs'">
									<image :src="n.url" :style="'width:'+n.w+'rpx'" mode="widthFix" v-for="(n,v) in item.content.list" :key="v" @click="showPic(n)"></image>
								</view>
								<!-- 单图 -->
								<view class="img" v-if="item.type=='img'">
									<image :src="item.content.url" :style="'width:'+item.content.w+'rpx'" mode="widthFix" @click="showPic(item.content)"></image>
								</view>
								<!-- 文字图片 -->
								<view class="text" v-if="item.type=='text'">
									<rich-text :nodes="item.content.text"></rich-text>
								</view>
								<!-- 语音消息 -->
								<view class="voice" v-if="item.type=='voice'" @click="playVoice(item,index)" :class="playMsgid == index?'play':''">
									<view class="length">{{item.content.length}}</view>
									<view class="icon my-voice"></view>
								</view>
								<!-- 文件 -->
								<view class="file" v-if="item.type=='file'">
									<view class="con u-flex u-flex-y-center" @click="openFile(item.content)">
										<view>
											<view class="tit">{{item.content.name}}</view>
											<view class="ftime">{{item.content.time}}</view>
										</view>
										<image :src="'/static/lj/common/file'+item.content.type+'.png'" mode=aspectFill></image>
									</view>
									<view class="foot u-flex u-flex-y-center">
										<image src="/static/lj/common/filelogo.png" mode="aspectFill"></image>
										<view>维普医疗</view>
									</view>
								</view>
								<!-- 电子处方 -->
								<view class="dzcf" v-if="item.type=='dzcf'" @click="toDrug(item.content.cf_id)">
									<view class="title">
										<image :src="'/static/cf-icon'+(((isDoc==1?item.from.prefix=='DT':item.from.prefix=='HZ')&&item.from.uid==FromUser.uid)?'-w':'')+'.png'" mode="aspectFill">
										<text>电子处方</text>
									</view>
									<view class="textCard">
										<view class="row" v-for="(n,v) in item.content.list" :key="v">
											<view class="left">{{n.name}}</view>
											<view class="right">{{n.value}}</view>
										</view>
									</view>
									<view class="bottom" v-if="isDoc!=1">
										<navigator :url="'/pagesA/drug/info?id='+item.content.cf_id">领取药方</navigator>
									</view>
								</view>
							</view>
						</view>

						<!-- 右-头像 -->
						<!--  -->
						<view class="avatar"><image :src="FromUser.avatar" v-if="((isDoc==1?item.from.prefix=='DT':item.from.prefix=='HZ')&&item.from.uid==FromUser.uid)"></image></view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<style lang="scss">
	// @import "@/static/message/static/HM-chat/css/style.scss";
	@import "chat.scss";

</style>

<script>
	export default {
		data() {
			return {
				pwappid: '',
				pwpage: '',
				jkscappid: '',
				jkscpage: '',
				
				orderInfo: null,
				orderStatus: -1, //0.待接诊

				waitTimestamp: 24*60*60, //待接诊时间
				consultTimestamp: 4*60*60, //咨询时间
				waitTimestampTimer: null,
				consultTimestampTimer: null,

				http_img: '',

				isDoc: 0,
				cate: "text",
				orderno: "",
				chatList: [],
				chatImgList: [],
				FromUser: {},
				ToUser: {},

				timePointerSize: 2*60,//2分钟时间范围内不增加时间显示
				timePointer: 0, //时间指针，用于是否显示时间
				downTimeTxt: "", //倒计时

				contentTop: 0,
				contentBottom: 0,
				contentInitBottom: 206,
				textareaFocus: true,
				textareaPrevLineCount: 1, //前一次的行高
				textareaAutoHeight: true, //文本输入框自增高
				showVoice: false, //显示录音
				showEmojiMode: false, //显示表情模块
				showMoreMode: false, //显示更多模块

				// 录音参数
				// #ifdef H5
				//H5不能录音
				RECORDER: null,
				// #endif
				// #ifndef H5
				//H5不能录音
				RECORDER: uni.getRecorderManager(),
				// #endif
				voiceBeginLock: false,
				recording: false,
				recordY: 0, //按住说话时的高度，用于上滑取消发送
				willStop: false,
				recordTimer: null, //录音计时器

				//播放语音相关参数
				AUDIO: uni.createInnerAudioContext(),
				playMsgid: null,

				//消息
				scrollAnimation: true,
				isHistoryLoading: false,
				scrollTop: 0,
				scrollToView: '',

				emojiList: [],

				textMsg: "",

				showCommentTip: true,
				
				showFilePop: false,
			}
		},
		onLoad(option) { //只加载一次
			var that = this
			
			that.$Http({
				url: 'getOthMiniConfig',
				data: {},
				token: false
			}).then(res => {
				if (res.code == 1) {
					that.pwappid = res.data.pwappid
					that.pwpage = res.data.pwpage
					that.jkscappid = res.data.jkscappid
					that.jkscpage = res.data.jkscpage
				}
			});

			that.http_img = that.$store.state.http_img
			that.emojiList = that.$store.state.emojiData
			// if(option.isDoc==1 && this.$store.state.userDoc.uid==0) return false;
			that.isDoc = option.isDoc==1?1:0;
			that.cate = option.cate
			that.orderno = option.orderno
			console.log('chat~')

			that.init()
		},
		onShow: function() {},
		onReady() { //只加载一次
		},
		onHide(){
			console.log('监听页面隐藏');
		},
		onUnload(){
			console.log('监听页面卸载');
		},
		methods:{
			gotoMini(appid, page){
				uni.navigateToMiniProgram({
					appId: appid,
					path: page,
					success(e) {
						console.log('gotoMini', e)
					},
					fail(e) {
						console.log('gotoMini fail',e)
					}
				})
			},
			sendMsg(type, content){
			},
			init(){
				var that = this
				// ~~~~ 测试参数 后期删除或注释
				// this.isDoc=1
				// this.cate='text'
				// this.orderno='2108190410495808871426'
				// ~~~~

				if(this.cate=='text'){//图文问诊
					this.$Http({
						url: this.isDoc?'doctordetailsConsultationOrder':'detailsConsultationOrder',
						type: 'POST',
						data: {order_code:this.orderno}
					}).then(res => {
						if(res.code==1) that.chatInit(res.data)
						else{
							uni.showToast({
								icon: 'none',
								duration: 3000,
								title: res.msg
							});
						}
					})
				}else if(this.cate=='video'){//视频问诊
					this.$Http({
						url: this.isDoc?'doctordetailsConsultationVideoOrder':'detailsConsultationVideoOrder',
						type: 'POST',
						data: {order_code:this.orderno}
					}).then(res => {
						if(res.code==1) that.chatInit(res.data)
						else{
							uni.showToast({
								icon: 'none',
								duration: 3000,
								title: res.msg
							});
						}
					})
				}else if(this.cate=='report'){//报告解读
					this.$Http({
						url: this.isDoc?'doctordetailsConsultationReportOrder':'detailsConsultationReportOrder',
						type: 'POST',
						data: {order_code:this.orderno}
					}).then(res => {
						if(res.code==1) that.chatInit(res.data)
						else{
							uni.showToast({
								icon: 'none',
								duration: 3000,
								title: res.msg
							});
						}
					})
				}else{
					uni.showToast({
						icon: 'none',
						duration: 3000,
						title: '参数错误.'
					});
				}
			},
			chatInit(orderInfo){
				console.debug("正在连接聊天室...")
				var that = this
				if(!orderInfo){
					uni.showToast({
						icon: 'none',
						duration: 3000,
						title: '问诊订单不存在~'
					});
					return false
				}
				that.orderInfo = orderInfo;
				// 未付款的订单查询不到

				orderInfo.user_the_patient_info = orderInfo.user_the_patient_info?orderInfo.user_the_patient_info:orderInfo.user_the_patient
				orderInfo.user_the_patient_info.age = that.$base.Onage(orderInfo.user_the_patient_info.birthday)
				
				if(that.isDoc==1){
					that.FromUser = that.$store.state.userDoc
					that.ToUser = {
						prefix: "HZ",
						uid: that.orderInfo.user_info.id,
						// nick: that.orderInfo.user_info.nickname,
						nick: that.orderInfo.user_the_patient_info.name,
						avatar: that.orderInfo.user_info.headimgurl
					}
					uni.setNavigationBarTitle({
						title: '患者 - ' + that.ToUser.nick
					});
				}else{
					that.FromUser = that.$store.state.user
					if(that.orderInfo.doctor_info){
						that.ToUser = {
							prefix: "DT",
							uid: that.orderInfo.doctor_info.user_id,
							nick: that.orderInfo.doctor_info.name,
							avatar: that.$store.state.http_img + that.orderInfo.doctor_info.img
						}
						uni.setNavigationBarTitle({
							title: that.ToUser.nick+'医生'
						});
					}else if(that.orderInfo.is_grab){
						uni.setNavigationBarTitle({
							title: '极速问诊'
						});
					}else{
						uni.setNavigationBarTitle({
							title: '详情'
						});
					}
				}

				// pay_status 支付状态1-已支付,2-未支付
				// status 状态:normal=正常,refund=已退款,cancel=已取消,refuse_patient=拒绝接诊,patient=接诊,end=完成接诊,comment=已评论
				// that.orderStatus = -3 //已取消，医生接诊超时
				// that.orderStatus = -2 //已取消，用户主动取消
				// that.orderStatus = -1 //医生拒绝接诊
				// that.orderStatus = 0 //待接诊
				// that.orderStatus = 1 //咨询/接诊中
				// that.orderStatus = 2 //问诊结束
				switch(orderInfo.status){
					case 'normal': //正常
						that.orderStatus = 0 //待接诊
						if( orderInfo.no_patient_timing <= 0 ) that.orderStatus = -3 //已取消，用户主动取消
						console.log('待接诊')
					break;
					case 'patient': //接诊
						that.orderStatus = 1 //咨询/接诊中
						if( orderInfo.patient_timing <= 0 ) that.orderStatus = 2 //问诊结束
					break;
					case 'refuse_patient': //拒绝接诊
						that.orderStatus = -1 //医生拒绝接诊
					break;
					case 'end': //完成接诊
						that.orderStatus = 2 //问诊结束
					break;
					case 'comment': //已评论
						that.orderStatus = 2 //问诊结束
					break;
					case 'cancel': //已取消
						// that.orderStatus = -3 //已取消，医生接诊超时
						that.orderStatus = -2 //已取消，用户主动取消
					break;
					case 'refund': //已退款
						// that.orderStatus = -3 //已取消，医生接诊超时
						that.orderStatus = -2 //已取消，用户主动取消
					break;
				}

				that.getChatHistory()
			},
			// 播放语音
			playVoice(item,index){
				console.log(item,index)
				if(this.playMsgid==index){
					this.AUDIO.stop();
					this.playMsgid=null;
					return
				}
				this.playMsgid = index;
				this.AUDIO.src = item.content.url;
				// this.$nextTick(function() {
					this.AUDIO.play();
				// });
			},

			// 触发滑动到顶部(加载历史记录)
			loadHistory(e){
				return
				if(this.isHistoryLoading) return
				var that = this

				this.isHistoryLoading = true;//参数作为进入请求标识，防止重复请求
				this.scrollAnimation = false;//关闭滑动动画

				// if(this.msgList == []){
				// 	let Viewid = 0;
				// }else{
				// 	let Viewid = this.msgList[0].msg.id;//记住第一个信息ID
				// }
				setTimeout(function(){
					that.scrollAnimation = true;//恢复滚动动画
					that.isHistoryLoading = false;
				},3000)
			},

			// 预览图片
			showPic(item){
				uni.previewImage({
					indicator:"none",
					current: item.url,
					urls: this.chatImgList
				});
			},
			// 跳转
			toHz(){
				var type = 'text'
				if(this.cate=='text') type = 'tw'
				else if(this.cate=='video') type = 'sp'
				else if(this.cate=='report') type = 'report'
				uni.navigateTo({
					url: '/pagesA/doctor/textinfo?type='+type+'&id=' + this.orderInfo.id,
				})
			},
			toDrug(cf_id){
				if(!this.isDoc) return false;
				uni.navigateTo({
					url: '/pagesA/prescript/doctorOrderDetail?id='+cf_id,
				})
			},

			getChatHistory(){
				var that = this
				this.$Http({
					url: 'chatHistory',
					type: 'POST',
					show: true,
					data: {orderno:this.orderno,isDoc:this.isDoc,cate:this.cate}
				}).then(res => {
					if(res.code==1){
						var chatList = [];
						var idx = -1;
						for(var i in res.data){
							try{
								var chat = JSON.parse(res.data[i].message).msg;
								console.log(chat)
								if(chat.time - that.timePointer>that.timePointerSize){ //时间范围内不增加时间显示
									chatList.push({
										cate: that.cate,
										orderno: that.orderno,
										fromType: 'system',
										type: 'time',
										content: {
											text: that.$base.__formatTime(chat.time)
										},
									})
								}
								that.timePointer = chat.time

								if(chat.type=='img'){
									// chat.content = that.setPicSize(chat.content)
									that.chatImgList.push(chat.content.url)
								}
								if(chat.type=='imgs'){
									if(idx<0) idx = i

									for(var j in chat.content.list){
										// chat.content.list[j] = that.setPicSize(chat.content.list[j])
										that.chatImgList.push(chat.content.list[j].url)
									}
								}
								chatList.push(chat)
							} catch(e) {
								console.log('getChatHistory error: ', e);
							}
						}

						that.chatList = chatList

						if(that.orderStatus==1){
							that.$nextTick(function() {
								that.scrollToView = "chat-"+(that.chatList.length-1)
							})
						}
					}
				})
			},

			// 计算年龄
			ages(str){
				var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
				if(r==null) return 0;
				var d= new Date(r[1], r[3]-1, r[4]);
				if(d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]){
					var age = new Date().getFullYear() - r[1];
					return age>0?age:0
				}
				return 0;
			},
			formatSeconds(value,format,isFull) {
				var sec = parseInt(value);// 秒
				var minutes = 0;// 分
				var hour = 0;// 小时

				if(isFull){
					if(sec > 60) {
						minutes = parseInt(sec/60);
						sec = parseInt(sec%60);
						if(minutes > 60) {
							hour = parseInt(minutes/60);
							minutes = parseInt(minutes%60);
						}
					}
				}else{
					hour = parseInt(sec/3600)
					sec -= hour*3600
					minutes = parseInt(sec/60)
					sec -= minutes*60
				}

				var result = ""
				for(var i in format){
					if(i == 'h' && hour>0){
						result += (hour<10&&isFull?'0'+hour:hour)+format[i];
					}
					if(i == 'i' && (minutes>0 || result)){
						if(isFull || minutes>0) result += (minutes<10&&isFull?'0'+minutes:minutes)+format[i];
					}
					if(i == 's' && (sec>0 || result)){
						if(isFull || sec>0) result += (sec<10&&isFull?'0'+sec:sec)+format[i];
					}
				}

				return result;
			},
			//处理图片尺寸，如果不处理宽高，新进入页面加载图片时候会闪
			async setPicSize(content){
				console.log('^^^^^ setPicSize',content)
				await uni.getImageInfo({
					src: content.url,
					success: function(image){
						content.w = image.width
						content.h = image.height

						// 让图片最长边等于设置的最大长度，短边等比例缩小，图片控件真实改变，区别于aspectFit方式。
						let maxW = uni.upx2px(350);//350是定义消息图片最大宽度
						let maxH = uni.upx2px(350);//350是定义消息图片最大高度
						if(content.w>maxW||content.h>maxH){
							let scale = content.w/content.h;
							content.w = scale>1?maxW:maxH*scale;
							content.h = scale>1?maxW/scale:maxH;
						}
						return content;
					},
					fail: function(msg){
						return content
					}
				})
			},
			
			// 判断文件类型
			whatFileType(url){
				let sr = url.lastIndexOf('.') //  最后一次出现的位置
				let fileType = url.substr((sr+1)) // 截取url的类型
				return(fileType)
			},
			openFile(item){
				console.log('openFile',item)
				var that = this
				if(item.type=='pdf'){
					uni.showLoading({
						title: '加载中',
						mask: true
					})
					
					let fileType = this.whatFileType(item.url)
					console.log(wx.env.USER_DATA_PATH + "/"+ (new Date().getTime()) + "."+fileType)
					uni.downloadFile({
						url: that.$base.img(item.url),
						// filePath: wx.env.USER_DATA_PATH + "/"+ (new Date().getTime()) + "."+fileType,
						success(res){
							uni.hideLoading()
							var filePath = res.tempFilePath
							uni.showLoading({
								title: '正在打开',
								mask: true
							})
							
							uni.openDocument({
								filePath: filePath,
								// fileType: item.type,
								// showMenu: true,
								// flieType: fileType,
								success(res) {
									uni.hideLoading()
									
								},
								fail(err){
									console.log('openDocument', err)
									uni.hideLoading()
									that.$u.toast('打开失败');
								}
							})
						},
						fail(err){
							console.log('downloadFile', err)
							uni.hideLoading()
							that.$u.toast('加载失败');
						}
					})
				}else{
					that.$u.toast('开始下载【'+item.name+'】');
					uni.downloadFile({
						url: that.$base.img(item.url),
						success: (res) => {
							if (res.statusCode === 200) {
								console.log('下载成功');
								that.$u.toast('下载成功');
							}
						}
					})
				}
			},
		}
	}
</script>
